﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using YmtAuth.AppService.Model;
using YmtSystem.CrossCutting;

namespace YmtAuth.AppService.ThirdPartyService
{
    public class DeviceIdService
    {
        public const string baseUri = "http://deviceid.iapi.ymatou.com";

        /// <summary>
        /// 根据deviceid获取deviceinfo
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public static GetDeviceinfoResponse GetDeviceinfo(string deviceId)
        {
            if (string.IsNullOrEmpty(deviceId)) return null;

            string url = string.Format("{0}/get?deviceId={1}&type=1", baseUri, deviceId);

            WebClient wc = new WebClient();
            string resJson = wc.DownloadString(url);

            return JsonConvert.DeserializeObject<GetDeviceinfoResponse>(resJson);
        }

        /// <summary>
        /// 更新DeviceId信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="deviceId"></param>
        /// <param name="did"></param>
        /// <returns></returns>
        public static void UpdateDeviceinfo(int userId, string deviceId, string did = null)
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                Dictionary<string, object> postData = new Dictionary<string, object>();
                postData.Add("deviceid", deviceId);
                postData.Add("userid", userId);

                if (userId <= 0 || string.IsNullOrEmpty(deviceId))
                {
                    YmatouLoggingService.Debug("【设备号服务】 UpdateDeviceinfo error, either userid or deviceId is invalid; {0}", JsonConvert.SerializeObject(postData));
                    return;
                }

                if (!string.IsNullOrEmpty(did))
                {
                    postData.Add("did", did);
                }

                byte[] postDataBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData));//编码，尤其是汉字，事先要看下抓取网页的编码方式  
                WebClient webClient = new WebClient();
                webClient.Headers.Add("Content-Type", "application/json");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可 

                string url = string.Concat(baseUri, "/update");

                byte[] responseData = webClient.UploadData(url, "POST", postDataBytes);//得到返回字符流  
                string resJson = Encoding.UTF8.GetString(responseData);//解码  

                YmatouLoggingService.Debug("【设备号服务】 UpdateDeviceinfo success, userId: {0}, deviceId: {1}, did: {2}; result: {3}", userId, deviceId, did, resJson);
            }).ContinueWith(
                    task =>
                    YmatouLoggingService.Error(string.Format("【设备号服务】 UpdateDeviceinfo error, userId: {0}, deviceId: {1}, did: {2}, error msg: {3}", userId, deviceId, did, task.Exception.Message), task.Exception),
                    TaskContinuationOptions.OnlyOnFaulted);
        }
    }
}
